import { _decorator, Component, Node, CCFloat, Vec3, RigidBody, Enum, SkinningModelComponent, Material, ERigidBodyType, ITriggerEvent, ColliderComponent, ICollisionEvent } from 'cc';
import { poolManager } from '../../../Framework/Scripts/Managers/poolManager';
import { ResMgr } from '../../../Framework/Scripts/Managers/ResMgr';
import { TimerMgr } from '../../../Framework/Scripts/Managers/TimerMgr';
import myUtil from '../../../Framework/Scripts/Utils/myUtil';
import { Vector3 } from '../../../Framework/Scripts/Utils/Vector3';

import { constant, OBJ_TYPE, PHY_GROUP } from '../constant';
import { GameApp } from '../GameApp';
import { buildingCtrl } from './buildingCtrl';
import { enemyModel } from './enemyModel';
import { MonsterBloodBar } from './fight/monsterBloodBar';
import { FightTip } from './fightTip';
import MapNavAgent from './MapNavAgent';
import { playerBase } from './playerBase';
import { Reward } from './reward';
interface NodeData {
    x: number;
    z: number;
    g: number;
    h: number;
    f: number;
    parent: NodeData | null;
}
const { ccclass, property } = _decorator;
const _vector1 = /*@__PURE__*/ new Vec3();
const _vector2 = /*@__PURE__*/ new Vec3();
const enum ENEMY_STATE {

    attack = 1,//攻击目标

    enemy_pursuit = 2,//敌人 追击
    pursuit_building = 3,//追击建筑物
    idle = 4//站立不动

}

const enum FRIENDLY_STATE {

    attack = 1,//攻击目标

    pursuit_enemy = 2,//友军 追击

    idle = 3//站立不动

}



let v3_tipsOffsetPos = new Vec3(-50, 175, 0);//血量提示距离小怪位置
let v3_monsterBloodOffsetPos = new Vec3(0, 120, 0);//血条距离小怪节点位置
let v3_monsterBloodScale = new Vec3(1, 1, 1);//小怪血条缩放大小
@ccclass('enemyBase')


export class enemyBase extends Component {
    private posY: number = 0
    private tipTimer: number = null
    private isShowTip: boolean = false
    protected isAttack: boolean = false

    //  protected isAttackNoIsBack: boolean = false
    @property({ type: CCFloat, displayName: "被攻击的距离加成" })
    protected hitSub: number = 0;

    @property()
    public isFangyu: boolean = false

    @property({ type: Enum(OBJ_TYPE), displayName: "角色类型" })
    public obj_type: OBJ_TYPE = OBJ_TYPE.enemy;


    @property({ type: CCFloat, displayName: "砍人的伤害" })
    protected hitNum: number = 15;

    @property({ type: CCFloat, displayName: "视野范围" })
    protected SightRange: number = 25;
    @property({ type: CCFloat, displayName: "攻击范围" })
    protected AttackRange: number = 6
    @property({ type: CCFloat, displayName: "移动速度" })
    protected speed: number = 2//移动速度

    @property({ type: CCFloat, displayName: "血量" })
    protected hp: number = 100//血量

    @property({ type: CCFloat, displayName: "缩放比例" })
    protected scale: number = 0.2//缩放比例



    @property({ displayName: "行走动画" })
    protected walkAni: string = "run"

    @property({ displayName: "攻击动画1" })
    protected attackAni1: string = "attack"

    @property({ displayName: "攻击动画2" })
    protected attackAni2: string = "attack2"

    @property({ displayName: "死亡动画" })
    protected dieAni: string = "died"

    @property({ displayName: "站立动画" })
    protected idelAni: string = "idle"


    @property({ type: CCFloat, displayName: "攻击建筑距离加成" })
    private bulidingLenAdd: number = 100
    @property(SkinningModelComponent)
    public model: SkinningModelComponent = null!;//蒙皮网格渲染器组件
    @property([Material])
    public aryMaterial: Material[] = [];//材质皮肤数组
    // public useNav: boolean = false


    //  private isOverInit:boolean=false
    public openNum: number = 1
    private isfirstHit: boolean = false
    protected nowAttackAni: string = "attack"
    protected nowAttackRange = 0//当前攻击范围
    public isDie: boolean = false

    protected enemyModel: enemyModel = null
    protected oldSpeen: number = 0
    protected isKuangbao: boolean = false//当前状态是否为狂暴
    protected playerTarget: Node = null
    protected buildingTarget: Node = null

    private oldHp: number = 0


    protected enemy_state: number = -1

    protected friendly_state: number = -1

    protected attackTarget: Node = null//当前攻击对象

    protected AI_delay: number = 0.3//ai思考时间
    protected timeADD: number = 0

    protected NavTs: MapNavAgent = null//导航


    protected totalHP: number = 0//起始血量

    protected isADD: boolean = false//引怪了

    protected pursuitRange_ADD: number = 0//相当于ADD时候怪物的主动追击距离

    protected scriptBloodBar: MonsterBloodBar = null
    protected bloodBar: Node = null;


    protected body: RigidBody = null;

    public agentId: number = 0
    protected isJiansu: boolean = false
    private _colliderCom: ColliderComponent = null!;//

    private isBack: boolean = false
    onLoad() {
        if (this.isFangyu) {
            return
        }
        this.posY = GameApp.Instance.playerTs.node.getPosition().y




        this.isJiansu = false
        this.oldSpeen = this.speed
        this.body = this.node.getComponent(RigidBody)
        this.enemyModel = this.node.getChildByName("body").getComponent(enemyModel)
        this.NavTs = this.node.getComponent(MapNavAgent)
        this._colliderCom = this.node.getComponent(ColliderComponent)




        this.SightRange *= this.SightRange
        this.AttackRange *= this.AttackRange
        this.totalHP = this.hp
        this.oldHp = this.hp



        this._colliderCom.on("onTriggerStay", this._onTriggerStayCb, this);


        this._colliderCom.on("onTriggerExit", this._onTriggerEndCb, this);






    }

    private _onTriggerEndCb(event: ICollisionEvent) {
        if (this.isDie) {
            return
        }
        this.scheduleOnce(() => {
            if (this.node) {
                this.isBack = false
            }

        }, 0.5)




    }
    private _onTriggerStayCb(event: ICollisionEvent) {
        //   console.log("碰撞1");

        if (this.isDie) {
            this.isBack = false
            //  console.log("碰撞2");
            return;
        }
        if (this.isBack) {
            //   console.log("碰撞3");
            return;
        }


        if (this.isAttack) {
            //this.isAttackNoIsBack = true
            return
        }
        const other: Node = event.otherCollider.node
        if (!other) {
            //    console.log("碰撞4");
            return
        }
        if (!other.getComponent(enemyBase)) {
            // console.log("碰撞5");
            return
        }
        if (other.getComponent(enemyBase).obj_type == this.obj_type) {
            //是友军
            this.back(other)

        }


    }
    // 避开目标
    // 避开目标
    private back(other: Node) {
        if (!other) {
            //  console.log("碰撞6");
            return;
        }
        if (!other.getComponent(enemyBase)) {
            // console.log("碰撞7");
            return;
        }

        const myPos: Vec3 = this.node.getWorldPosition();
        const otherPos: Vec3 = other.getWorldPosition();
        const toOther: Vec3 = Vector3.sub(otherPos, myPos);
        const forwardDot: number = Vector3.dot(this.node.forward, toOther);
        if (forwardDot < 0) { // 在前
            //  console.log("碰撞8");
            return;
        }

        // 使用叉乘计算右侧向量
        const crossProduct: Vec3 = Vector3.cross(this.node.forward, toOther);
        let right: Vec3 = null;

        // 判断叉乘结果的y分量以确定左右方向
        if (crossProduct.y < 0) {
            right = new Vec3(this.node.forward.z, 0, -this.node.forward.x).normalize();
        } else {
            right = new Vec3(-this.node.forward.z, 0, this.node.forward.x).normalize();
        }
        if (!right) {
            //  console.log("碰撞9");

            return
        }
        this.isBack = true;

        const pos: Vec3 = Vector3.add(myPos, Vector3.mul(right, 5));
        this.NavTs.NavOnRoad([pos]);
    }













    // }
    start() {

    }


    /**
 * 展示小怪血条
 *  
 * @param {*} scriptParent 
 * @param {number} totalBlood
 * @param {number} bloodBarType
 * @param {Function} [callback=()=>{}]
 * @param {Vec3} [offsetPos=MONSTER_BLOOD_OFFSET_POS]
 * @param {Vec3} [scale=MONSTER_BLOOD_SCALE]
 * @memberof uiManager
 */
    protected showMonsterBloodBar(totalBlood: number, callback: Function = () => { }, offsetPos: Vec3 = v3_monsterBloodOffsetPos, scale: Vec3 = v3_monsterBloodScale) {
        // console.log();
        if (!this.bloodBar) {
            this.bloodBar = poolManager.instance.getNode(ResMgr.Instance.getAsset("GUI", "fight/monsterBloodBar"), GameApp.Instance.bloodBar_root);
            // this.bloodBar.getComponent(UIOpacity).opacity=0
            //   console.log("血条：", this.bloodBar);


        }
        if (!this.scriptBloodBar) {
            this.scriptBloodBar = this.bloodBar.getComponent(MonsterBloodBar) as MonsterBloodBar;

        }

        this.bloodBar.setPosition(1000, 1000, 1000)

        this.bloodBar.setScale(v3_monsterBloodScale)
        this.scriptBloodBar.show(this, totalBlood, offsetPos, scale, callback);





    }

    private initEnemy(playerTarget: Node, buildingTarget: Node) {


        this.playerTarget = playerTarget
        this.buildingTarget = buildingTarget
        this.attackTarget = this.buildingTarget
        this.totalHP = this.oldHp + (this.oldHp * constant.enemyHp * GameApp.Instance.level)

        this.hp = this.totalHP



        this.enemy_state = ENEMY_STATE.pursuit_building
    }

    private initFriendly() {
        //友军血量也随关卡增长
        this.totalHP = this.oldHp + (this.oldHp * constant.friendlyHp * GameApp.Instance.level)



        //友军等级
        const myLevel: number = constant.friendlyData[this.node.name]["level"]
        const add: number = constant.friendlyData[this.node.name]["PhAdd"]

        this.totalHP = this.totalHP * (1 + add * myLevel)





        this.hp = this.totalHP


    }

    public init(type: OBJ_TYPE, _agentId: number, setScale: number = 1) {

        if (this.tipTimer) {
            TimerMgr.Instance.UnSchedule(this.tipTimer)
            this.tipTimer = null
        }
        this.tipTimer = null
        this.isShowTip = false
        this.isJiansu = false
        this.isBack = false
        const pos: Vec3 = this.node.getPosition()
        this.node.setPosition(pos.x, this.posY, pos.z)
        this.isfirstHit = false
        this.agentId = _agentId  //寻路id
        this.isKuangbao = false
        this.node.setScale(new Vec3(this.scale * setScale, this.scale * setScale, this.scale * setScale))
        this.isADD = false



        this.isAttack = false
        this.nowAttackRange = this.AttackRange//当前攻击范围
        this.nowAttackAni = this.attackAni1

        this.pursuitRange_ADD = this.SightRange * 2//引怪的追击范围是正常视野范围的2倍


        //物理
        this.body.type = ERigidBodyType.KINEMATIC
        this.body.enabled = true



        this.speed = this.oldSpeen

        if (this.NavTs) {
            this.NavTs.InitMapNavAgent(this.speed)

        }



        switch (type) {

            case OBJ_TYPE.enemy:
                this.obj_type = OBJ_TYPE.enemy
                this.body.setGroup(PHY_GROUP.enemy)
                if (this.aryMaterial.length > 0 && this.model) {
                    //0蓝色 1红色 2黄色
                    this.model.material = this.aryMaterial[1];
                }
                this.node.getChildByName("minMap1").active = true
                this.node.getChildByName("minMap2").active = false
                this.initEnemy(GameApp.Instance.player, GameApp.Instance.building)
                break;

            case OBJ_TYPE.friendly:
                this.obj_type = OBJ_TYPE.friendly
                this.body.setGroup(PHY_GROUP.friendly)
                if (this.aryMaterial.length > 0 && this.model) {
                    this.model.material = this.aryMaterial[0];
                }
                this.node.getChildByName("minMap1").active = false
                this.node.getChildByName("minMap2").active = true
                this.initFriendly()
                break;

            default:

                break;
        }
        this.isDie = false

    }


    public attickCallback() { }//攻击动画回调

    public die() {
        if (GameApp.Instance.isGameOver) {
            return
        }
        if (this.tipTimer) {
            TimerMgr.Instance.UnSchedule(this.tipTimer)
            this.tipTimer = null
        }


        this.isDie = true
        if (this.bloodBar) {
            poolManager.instance.putNode(this.bloodBar)
            this.bloodBar = null
            this.scriptBloodBar = null
        }
        this.NavTs.StopNav()

        this.enemyModel.playAni(this.dieAni, false, () => {
            //  this.hp = this.totalHP
            if (this.obj_type == OBJ_TYPE.enemy) {
                //敌人阵亡更新进度条
                GameApp.Instance.subEnemyCount()
            }
            const r: number = Math.random()
            let rewardname: string = "coin"
            //必须掉落金币
            if (r < constant.heartA) {
                rewardname = "heartA"

            }

            if (rewardname) {
                const n: Node = poolManager.instance.getNode(ResMgr.Instance.getAsset("prefab", "prop/" + rewardname), this.node.parent)
                n.setWorldPosition(this.node.getWorldPosition())
                const ts: Reward = n.getComponent(Reward)
                if (ts) {
                    ts.init(0.3, this.node.parent)
                }
            }

            poolManager.instance.putNode(this.node)
        })

    }

    //怪物受到攻击
    public hit(num: number, howHit: Node, isStay?: boolean) {
        if (GameApp.Instance.isGameOver) {
            return
        }
        let hitNum: number = num
        if (GameApp.Instance.playerTs.isDie) {
            //玩家如果死亡不掉血
            return
        }
        if (this.isDie && (!howHit)) {
            return
        }
        const howHitTS: enemyBase = howHit.getComponent(enemyBase)

        if (howHitTS) {


            if (howHitTS.obj_type == this.obj_type) {

                return
            } else {

                if (howHitTS.obj_type === OBJ_TYPE.enemy) {
                    //说明敌方打的我
                    hitNum = hitNum + (hitNum * constant.enemyAttack * GameApp.Instance.level)

                } else if (howHitTS.obj_type === OBJ_TYPE.friendly) {
                    //这里写友军攻击力加成
                    if (!howHitTS.isFangyu) {

                        hitNum = hitNum + (hitNum * constant.friendlyAttack * GameApp.Instance.level)
                        const myLevel: number = constant.friendlyData[howHitTS.node.name]["level"]
                        const add: number = constant.friendlyData[howHitTS.node.name]["AttackAdd"]


                        hitNum = hitNum * (1 + add * myLevel)
                    } else {
                        hitNum = hitNum + (hitNum * constant.fangyuAttack * GameApp.Instance.level)
                        //如果是建筑
                    }



                }
            }
        }






        let isBaoji: boolean = false
        if (howHit.getComponent(playerBase)) {//如果是玩家打的计算减速伤害和暴击伤害
            const baoji: number = GameApp.Instance.playerData.baoji / 100

            const r: number = Math.random()
            if (r < baoji) {
                isBaoji = true
                const baojiADD: number = GameApp.Instance.playerData.config.baojiADD.level * 0.1 + 2
                hitNum *= baojiADD//暴击伤害动态更新

            }
            if (GameApp.Instance.playerData.jiansu > 0) {
                //有减速 额外造成伤害
                const jiansuADD: number = hitNum * (GameApp.Instance.playerData.jiansu / 100)

                hitNum += jiansuADD
            }
        }

        this.hp -= hitNum


        if (this.hp <= 0) {
            this.die()

            return
        }
        if (!this.isfirstHit) {
            this.isfirstHit = true
            if (this.obj_type === OBJ_TYPE.enemy) {
                this.showMonsterBloodBar(this.totalHP)

            }
        }
        if (this.scriptBloodBar) {

            this.scriptBloodBar.refreshBlood(-hitNum)

        }
        //显示伤害数字
        if (!this.isShowTip && howHit.getComponent(playerBase)) {
            this.tipTimer = null
            this.isShowTip = true


            const fightTip: Node = poolManager.instance.getNode(ResMgr.Instance.getAsset("GUI", "fight/fightTip"), GameApp.Instance.fightTip_root)

            const fightTipTS: FightTip = fightTip.getComponent(FightTip)
            if (fightTipTS) {


                let typ: number = constant.FIGHT_TIP.REDUCE_BLOOD
                if (isBaoji) {
                    //是暴击类型数字
                    typ = constant.FIGHT_TIP.CRITICAL_HIT
                }
                let Hit: number = Math.floor(hitNum)


                if (isStay) {


                    Hit = Math.floor(hitNum * 30)
                }
                if (Hit < GameApp.Instance.playerData.gongji) {
                    Hit = GameApp.Instance.playerData.gongji
                }
                fightTipTS.show(this.node.getWorldPosition(), typ, Hit)
            }
            this.tipTimer = TimerMgr.Instance.ScheduleOnce(() => {
                TimerMgr.Instance.UnSchedule(this.tipTimer)
                this.tipTimer = null
                this.isShowTip = false

            }, this, 0.5)
        }


        //被防御打了不追击
        if (howHitTS && howHitTS.isFangyu) {



            return
        }
        if (howHit) {
            this.isADD = true

            this.attackTarget = howHit
        }


        //处理减速效果
        if (this.isJiansu) {
            return
        }

        if (GameApp.Instance.playerData.jiansu <= 0) {
            return
        }
        if (!howHit) {
            return
        }
        //处理减速
        if (howHit.getComponent(playerBase)) {
            this.isJiansu = true
            this.speed -= this.speed * (GameApp.Instance.playerData.jiansu / 100)
            if (this.NavTs) {
                this.NavTs.InitMapNavAgent(this.speed)

            }
        }













    }




    protected getStatefriendly(): Number {

        //如果玩家挂了友军停在原地
        if (GameApp.Instance.playerTs.isDie) {
            this.friendly_state = FRIENDLY_STATE.idle
            return this.friendly_state
        }

        this.attackTarget = null
        this.attackTarget = this.findEnemy(GameApp.Instance.enemyRoot)


        if (this.attackTarget) {
            const len: Number = Vector3.sub(this.attackTarget.getWorldPosition(), this.node.getWorldPosition()).lengthSqr()
            let nowAttackRange2: number = this.nowAttackRange
            const ts: enemyBase = this.attackTarget.getComponent(enemyBase)
            if (ts) {
                nowAttackRange2 += ts.hitSub
            }
            this.friendly_state = FRIENDLY_STATE.pursuit_enemy
            if (len <= nowAttackRange2) {
                this.attackTarget = this.attackTarget
                this.friendly_state = FRIENDLY_STATE.attack
            }
        } else {
            this.friendly_state = FRIENDLY_STATE.idle
        }

        return this.friendly_state
    }

    protected getStateEnemy(): Number {
        const building_len: Number = Vector3.sub(this.buildingTarget.getWorldPosition(), this.node.getWorldPosition()).lengthSqr() - this.bulidingLenAdd


        if (this.attackTarget) {
            if (this.attackTarget.getComponent(enemyBase)) {
                if (this.attackTarget.getComponent(enemyBase).isDie) {
                    this.attackTarget = this.buildingTarget
                    this.enemy_state = ENEMY_STATE.pursuit_building

                    if (building_len <= this.nowAttackRange) {

                        //  this.attackTarget = this.buildingTarget
                        this.enemy_state = ENEMY_STATE.attack
                    } else {
                        this.enemy_state = ENEMY_STATE.enemy_pursuit
                    }
                    return this.enemy_state
                }
            }
        }


        if (GameApp.Instance.playerTs.isDie) {
            this.enemy_state = ENEMY_STATE.pursuit_building
            if (building_len <= this.nowAttackRange) {
                this.attackTarget = this.buildingTarget
                this.enemy_state = ENEMY_STATE.attack
            }
            return this.enemy_state
        }

        //引怪逻辑
        if (this.isADD && this.attackTarget) {


            const howHitLen: Number = Vector3.sub(this.attackTarget.getWorldPosition(), this.node.getWorldPosition()).lengthSqr()

            if (howHitLen >= this.pursuitRange_ADD) {
                this.isADD = false


                //引怪离得太远 够不着 直接打建筑物去
                this.enemy_state = ENEMY_STATE.pursuit_building

                if (building_len <= this.nowAttackRange) {
                    this.attackTarget = this.buildingTarget
                    this.enemy_state = ENEMY_STATE.attack
                }


            } else {
                let nowAttackRange2: number = this.nowAttackRange

                const ts: enemyBase = this.attackTarget.getComponent(enemyBase)
                if (ts) {
                    nowAttackRange2 += ts.hitSub
                }
                this.enemy_state = ENEMY_STATE.enemy_pursuit
                if (howHitLen <= (nowAttackRange2)) {

                    this.enemy_state = ENEMY_STATE.attack

                }
            }
            return this.enemy_state
        }





        // //  玩家和建筑同时在视野范围内

        const player_len: Number = Vector3.sub(this.playerTarget.getWorldPosition(), this.node.getWorldPosition()).lengthSqr()

        if (player_len <= this.SightRange && building_len <= this.SightRange) {





            this.enemy_state = ENEMY_STATE.pursuit_building

            if (building_len <= this.nowAttackRange) {


                this.attackTarget = this.buildingTarget
                this.enemy_state = ENEMY_STATE.attack
            }
            return this.enemy_state

        }


        if (player_len <= this.SightRange) {



            this.enemy_state = ENEMY_STATE.enemy_pursuit
            if (player_len <= this.nowAttackRange) {
                this.attackTarget = this.playerTarget
                this.enemy_state = ENEMY_STATE.attack

            }
        } else {


            this.enemy_state = ENEMY_STATE.pursuit_building

            if (building_len <= this.nowAttackRange) {
                this.attackTarget = this.buildingTarget
                this.enemy_state = ENEMY_STATE.attack
            }
        }










        return this.enemy_state
    }

    protected pursuit_building() {
        this.isADD = false
        //相当于停止移动



        this.NavTs.StopNav()
        this.NavTs.NavOnRoad([this.buildingTarget.getWorldPosition()])

        this.enemyModel.playAni(this.walkAni, true)


    }
    //敌人得追击逻辑
    protected enemy_pursuit() {

        if (!this.attackTarget) {
            return
        }







        this.NavTs.StopNav()
        this.NavTs.NavOnRoad([this.attackTarget.getWorldPosition()])

        this.enemyModel.playAni(this.walkAni, true)

    }
    //友军的追击逻辑
    protected friendly_pursuit() {
        if (!this.attackTarget) {
            return
        }
        this.enemyModel.playAni(this.walkAni, true)

        this.NavTs.StopNav()
        this.NavTs.NavOnRoad([this.attackTarget.getWorldPosition()])

    }
    protected attack() {
        if (this.isDie) {
            return
        }




        this.NavTs.StopNav()



    }



    protected idle() {




        this.NavTs.StopNav()


        this.body.clearState()
        this.body.enabled = false

        this.enemyModel.playAni(this.idelAni, true)

    }
    //找敌人
    protected findEnemy(root: Node): Node {

        const n: Node = this.getNearestMonster(root.children)

        if (n) {
            return n
        } else {
            return this.getNearestMonster(root.children, true)
        }


    }

    /**
     * 获取距离最近的小怪、boss节点
     * @returns 
     */
    protected getNearestMonster(enemyArr: Node[], isAll: boolean = false) {


        if (enemyArr.length) {
            let arr = enemyArr.sort((a: any, b: any) => {
                let distanceA = myUtil.getTwoNodeXZLengthSqr(this.node, a);
                let distanceB = myUtil.getTwoNodeXZLengthSqr(this.node, b);
                return distanceA - distanceB;
            })

            arr = arr.filter((item: Node) => {
                let ts: enemyBase = null

                ts = item.getComponent(enemyBase);


                if (!isAll) {
                    return item.parent !== null && ts && !ts.isDie && ts.openNum == this.openNum

                } else {
                    return item.parent !== null && ts && !ts.isDie

                }
            })

            return arr[0];
        } else {
            //  console.log("没有怪了-------------------");

            return null;
        }
    }

    //普通攻击
    protected putonggognji() {

        if (!this.attackTarget) {
            return
        }
        if (!this.node) {
            return


        }
        this.NavTs.StopNav()
        this.node.lookAt(this.attackTarget.getWorldPosition())


        if (this.attackTarget.getComponent(playerBase)) {
            GameApp.Instance.playerTs.hit(this.hitNum, this.node)
            return
        }
        if (this.attackTarget.getComponent(enemyBase)) {
            this.attackTarget.getComponent(enemyBase).hit(this.hitNum, this.node)
            return
        }
        if (this.attackTarget.getComponent(buildingCtrl)) {
            this.attackTarget.getComponent(buildingCtrl).hit(this.hitNum)
            return
        }



    }

    update(dt: number) {
        if (GameApp.Instance.isGameOver) {
            return
        }
        if (this.isBack) {
            return
        }


        if (this.isDie || this.isFangyu) {
            return
        }




        this.timeADD += dt
        if (this.timeADD >= this.AI_delay) {
            this.timeADD = 0

            switch (this.obj_type) {
                case OBJ_TYPE.enemy:
                    if (this.playerTarget == null || this.buildingTarget == null) {
                        return
                    }

                    switch (this.getStateEnemy()) {



                        case ENEMY_STATE.attack:
                            this.isAttack = true
                            this.attack()
                            break;

                        case ENEMY_STATE.pursuit_building:
                            this.isAttack = false
                            this.pursuit_building()
                            break;

                        case ENEMY_STATE.enemy_pursuit:
                            this.isAttack = false
                            this.enemy_pursuit()
                            break;

                        case ENEMY_STATE.idle:
                            this.isAttack = false
                            this.idle()
                            break;

                        default:

                            this.idle()
                            break;
                    }
                    break;



                case OBJ_TYPE.friendly:


                    switch (this.getStatefriendly()) {
                        case FRIENDLY_STATE.pursuit_enemy:
                            //    console.log("我应该追击敌人",this.attackTarget);
                            this.friendly_pursuit()
                            break;

                        case FRIENDLY_STATE.attack:
                            //     console.log("我应该攻击敌人",this.attackTarget);

                            this.attack()
                            break;

                        case FRIENDLY_STATE.idle:
                            this.idle()
                            break;

                        default:
                            break;
                    }
                    break;
                default:
                    break

            }


        }



    }








    //一下是寻路代码
    isInBounds(navMesh: boolean[][], node: { x: number, z: number }): boolean {
        return node.x >= 0 && node.x < navMesh.length && node.z >= 0 && node.z < navMesh[0].length;
    }

    isWalkable(navMesh: boolean[][], node: NodeData): boolean {
        return navMesh[node.x] && navMesh[node.x][node.z];
    }
    findPath(navMesh: boolean[][], start: Vec3, end: Vec3): Vec3[] {
        const openList: NodeData[] = [];
        const closedList: NodeData[] = [];
        const startNode: NodeData = { x: start.x, z: start.z, g: 0, h: 0, f: 0, parent: null };
        const endNode: NodeData = { x: end.x, z: end.z, g: 0, h: 0, f: 0, parent: null };

        // console.log("开始寻路: ", startNode, endNode);

        if (!this.isWalkable(navMesh, startNode) || !this.isWalkable(navMesh, endNode)) {
            //   console.log("起点或终点不在可走区域内");
            return [];
        }

        openList.push(startNode);

        while (openList.length > 0) {
            let currentNode = openList.reduce((prev, curr) => (prev.f < curr.f ? prev : curr));

            //  console.log("当前节点: ", currentNode);

            if (currentNode.x === endNode.x && currentNode.z === endNode.z) {
                const path: Vec3[] = [];
                while (currentNode.parent) {
                    path.push(new Vec3(currentNode.x, 0, currentNode.z));
                    currentNode = currentNode.parent;
                }
                // console.log("找到路径: ", path);
                return path.reverse();
            }

            openList.splice(openList.indexOf(currentNode), 1);
            closedList.push(currentNode);

            const neighbors = [
                { x: currentNode.x + 1, z: currentNode.z },
                { x: currentNode.x - 1, z: currentNode.z },
                { x: currentNode.x, z: currentNode.z + 1 },
                { x: currentNode.x, z: currentNode.z - 1 },
            ];

            for (const neighbor of neighbors) {
                if (!this.isInBounds(navMesh, neighbor) || !navMesh[neighbor.x][neighbor.z]) {
                    continue;
                }

                if (closedList.find(node => node.x === neighbor.x && node.z === neighbor.z)) {
                    continue;
                }

                const g = currentNode.g + 1;
                const h = Math.abs(neighbor.x - endNode.x) + Math.abs(neighbor.z - endNode.z);
                const f = g + h;

                let neighborNode = openList.find(node => node.x === neighbor.x && node.z === neighbor.z);

                if (!neighborNode) {
                    neighborNode = { x: neighbor.x, z: neighbor.z, g, h, f, parent: currentNode };
                    openList.push(neighborNode);
                    //    console.log("添加邻居节点到openList: ", neighborNode);
                } else if (g < neighborNode.g) {
                    neighborNode.g = g;
                    neighborNode.f = f;
                    neighborNode.parent = currentNode;
                    //  console.log("更新邻居节点: ", neighborNode);
                }
            }
        }

        // console.log("未找到路径");
        return [];
    }





}


